const basePath = 'https://hqadmin.yuzhekeji.top/wechatApi'
// const basePath = 'http://192.168.10.43:10100/wechatApi'
var aes = require('./public.js')
var md5 = require("./md5/md5.js")
const app = getApp();

const http = ({
  url = '',
  accessToken = '',
  param = {},
  ...other
} = {}) => {
  // wx.showLoading({
  //   title: '请求中，请耐心等待..'
  // });
  let timeStart = Date.now();
  return new Promise((resolve, reject) => {
    var jsonStr = JSON.stringify(param);
    //加密请求参数
    var aesData = aes.Encrypt(jsonStr)
    wx.request({
      url: getUrl(url),
      data: {
        aesData: aesData
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded', // 默认值 ,另一种是 "content-type": "application/x-www-form-urlencoded"
        'access_token': accessToken
      },
      ...other,
      complete: (res) => {
        // wx.hideLoading();
        // console.log(getUrl(url))
        // console.log('kKKKK',res)
        if (res.statusCode === 200) {
          if (res.data.code === 500) {
            resolve(res.data)
            return
          }
          if (res.data.code === 401) {
            wx.navigateTo({
              url: '../authorize/index'
            })
            return
          }
          if (res.data.code !== 0) {
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            })
            return;
          }
          if (res.data.code === 0) {
            resolve(res.data)
          }
        } else {
          // wx.navigateTo({
          //   url: '../authorize/index'
          // })

          reject(res)
        }
      }
    })
  })
}

const getUrl = (url) => {
  if (url.indexOf('://') == -1) {
    url = basePath + url;
  }
  return url
}

// get方法
const _get = (url, param = {}) => {
  return http({
    url,
    param
  })
}

const _post = (url, accessToken, param = {}) => {
  return http({
    url,
    accessToken,
    param,
    method: 'post'
  })
}

const _put = (url, param = {}) => {
  return http({
    url,
    param,
    method: 'put'
  })
}

const _delete = (url, param = {}) => {
  return http({
    url,
    param,
    method: 'put'
  })
}

const _saveFormId = (formId) => {
  // return http({
  //   url: '/user/saveFormId',
  //   params,
  //   method: 'post'
  // })
  let params = {
    formId: formId,
    userId: wx.getStorageSync('userId')
  }
  wx.request({
    url: getUrl('/user/saveFormId'),
    header: {
      'content-type': 'application/x-www-form-urlencoded', // 默认值 ,另一种是 "content-type": "application/x-www-form-urlencoded"
    },
    data: params,
    method: "post",
    complete: (res) => {}
  })

}


module.exports = {
  basePath,
  _get,
  _post,
  _put,
  _delete,
  _saveFormId
}